const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())

app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(express.static('./public'))

// 集成log4js日志
const log4js = require('./utils/log4js')
const logger = log4js.getLogger('runtime')
// 错误统一处理
app.use((req, res, next) => {
  // 1 = 失败, 0 = 成功
  res.new_send = (err, status = 1) => {
    status === 1 ? logger.error(err) : logger.log(err)
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})

const { expressjwt } = require('express-jwt')
const config = require('./utils/config')
// 过滤Token校验接口
app.use(
  expressjwt({ secret: config.jwtSecretKey, algorithms: ['HS256'] }).unless({
    path: [/^\/blog/, /^\/test/]
  })
)

// 导入并注册用户路由模块
const router = require('./router')
app.use(router)

const joi = require('joi')
app.use((err, req, res, next) => {
  if (err instanceof joi.ValidationError) return res.new_send(err)
  if (err.name === 'UnauthorizedError') return res.new_send('身份认证失败', 99)
  res.new_send(err)
})

// 调用 app.listen 方法，指定端口号并启动web服务器
app.listen(8001, () => {
  console.log('后端(manage_api)服务 http://127.0.0.1:8001 运行中...')
})
